package com.tucc.hello.leetcode.no1_400.no1_200.no146;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {


    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] operations = {"LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"};
        int[][] operateNums = {{2}, {1, 1}, {2, 2}, {1}, {3, 3}, {2}, {4, 4}, {1}, {3}, {4}};
        solution.mockLRU(operations, operateNums);
    }

    public void mockLRU(String[] operations,
                        int[][] operateNums) {
        LRUCache lruCache = null;
        for (int i = 0; i < operations.length; i++) {
            int[] curNum = operateNums[i];
            if ("LRUCache".equals(operations[i])) {
                lruCache = new LRUCache(curNum[0]);
            } else if ("put".equals(operations[i])) {
                lruCache.put(curNum[0], curNum[1]);
            } else if ("get".equals(operations[i])) {
                System.out.println(lruCache.get(curNum[0]));
            }
        }
    }
}

class LRUCache {

    private Map<Integer, Integer> cache;

    private int capacity = 0;

    public LRUCache(int capacity) {
        cache = new LinkedHashMap<>(capacity, 1, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        Integer value = cache.get(key);
        return value == null ? -1 : value;
    }

    public void put(int key, int value) {
        cache.put(key, value);
        if (cache.size() > capacity) {
            Iterator iterator = cache.entrySet().iterator();
            iterator.next();
            iterator.remove();
        }
    }
}
